'''
Created on Apr 7, 2012

@author: e911miri
'''

import cherrypy
from jinja2 import Environment, FileSystemLoader
from config import users
import time
from helper import runQuery

env = Environment(loader=FileSystemLoader('templates/admin'))


class Admin():
    _cp_config = {
        'tools.sessions.on': True,
    }
    @cherrypy.expose
    @cherrypy.tools.allow(methods=['GET'])
    def index(self):
        tmpl = env.get_template('auth.html')
        return tmpl.render({})
    
    @cherrypy.expose
    @cherrypy.tools.allow(methods=['POST'])
    def login(self, user=None, pwd=None):
        if pwd == users[user]:
            cherrypy.session["user"] = "admin"
            cherrypy.session["logged_in"] = True
            tmpl = env.get_template("admin.html")
            r = {'target':cherrypy.session.get("user"), 'time': time.ctime()}
            return tmpl.render(r)
        else:   
            raise cherrypy.HTTPError(401, "You are not allowed to view this resource!")
        tmpl = env.get_template('auth.html')
        return tmpl.render({'error':'Invalid Credentials'})
       
    @cherrypy.expose
    def search(self, regnum=None):
        query = "select * from candidates join scores where reg_num= %s idscores = idcandidates limit 0,1"
        result = runQuery(query, (regnum,))
        if result:
            tmpl = env.get_template('result.html')
            return tmpl.render({'result': result})
        else:
            tmpl = env.get_template('result.html')
            return tmpl.render({'error': 'Registration Number not found, Create New??'})
        
    @cherrypy.expose
    def test(self):
        pass
#    @cherrypy.expose
#    def admin(self):
#        tmpl = env.get_template("admin.html")
#        return tmpl.render()
